// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
// 云函数入口函数
const db = cloud.database();
const _  = db.command
const collection = db.collection('groupAction');
function calculateOverlapTimeWithRange(objArray) {
    // Step 1: Sort the array by startTime
    objArray.sort((a, b) => a.startTime - b.startTime);
  
    // Step 2: Initialize current max end time with the end time of the first object
    let currentMaxEndTime = objArray[0].endTime;
    let overlapStartTime = null;
    let overlapEndTime = null;
  
    // Step 3-4: Traverse the array and update current max end time and overlap time
    let overlapTime = 0;
    for (let i = 1; i < objArray.length; i++) {
      const obj = objArray[i];
      if (obj.startTime > currentMaxEndTime) {
        // No overlap
        if (overlapStartTime !== null) {
          // There was overlap with the previous objects
          overlapEndTime = currentMaxEndTime;
          overlapTime += overlapEndTime - overlapStartTime;
          overlapStartTime = null;
          overlapEndTime = null;
        }
        currentMaxEndTime = obj.endTime;
      } else {
        // Overlap
        if (overlapStartTime === null) {
          // This is the beginning of a new overlap period
          overlapStartTime = obj.startTime;
        }
        overlapEndTime = Math.min(obj.endTime, currentMaxEndTime);
        overlapTime += overlapEndTime - obj.startTime;
        currentMaxEndTime = Math.max(currentMaxEndTime, obj.endTime);
      }
    }
  
    // If the last object had overlap with the previous objects
    if (overlapStartTime !== null) {
      overlapEndTime = currentMaxEndTime;
      overlapTime += overlapEndTime - overlapStartTime;
    }
  
    // Step 5: Return the overlap time and range
    return {
      overlapTime,
      overlapRange: {
        startTime: overlapStartTime,
        endTime: overlapEndTime,
      },
    };
  }
  
// Define the function that sends the reminder message
async function sendReminderMessage(activity) {
    const record = await collection.doc(activity.id).get();
    if (!record.data) {
      return {
        code: 404,
        message: `Record with id ${id} not found`
      };
    }
    let time = calculateOverlapTimeWithRange(record.data.member)
  
    // 判断重合区间是否大于或等于一个小时
    const oneHour = 60 * 61 * 1000;
    if (time.overlapTime >= oneHour) {
      // 遍历数组，更新用户日程
      for (const member of record.data.member) {
        await cloud.callFunction({
          name: 'userSchduleService',
          data: {
            _openid: "oIkn44pF_P_pj1_d9Lzmdh_3wA04" || 1,
            activateDate:record.data.setedTime||time.overlapRange.startTime,
            phone:18628525985,
            tag:2,
            startTime:record.data.setStartTime||time.overlapRange.startTime,
            endTime:record.data.setEndTime||time.overlapRange.endTime,
            isDone: 0,
            type:6,
            isRepreatType:0,
            needRemind:true,
            description:record.data.description,
            group: record.data._id
        }
        });
      }
    } else {
      // 重合区间小于一个小时，标记记录为已完成
      await collection.doc(record.data._id).update({
        data: {
            isDone: 2
            }
            });
            return {
            code: 200,
            message:` Record with id ${record.data._id} marked as done`
            };
            }
            // 返回结果
            return {
            code: 200,
            message: `Overlap interval for record with id ${record.data._id}: ${time.overlapRange.startTime} - ${time.overlapRange.endTime}`
            };
  }
  
  // Define the function that schedules the task
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    let res = await db.collection("groupAction").where({
        isDone:0
    }).get()
    if (!res.data|| res.data.length<=0){
        return {
            "code":200,
            "msg":"success to create schedule task"
        }
    }
    for(let  h = 0 ; h<res.data.length;h++){
        await sendReminderMessage({id:res.data[h]["_id"]})
        
    }
    await collection.where({
        isDone:0
    }).update({
        data: {
            isDone: 1
            }
            })
    return {
        "code":200,
        "msg":"success to create schedule task"
    }
}